package com.hobson.design.factory.builder;

import com.hobson.design.factory.exception.BizException;

import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 默认订单建造者实现
 * @author: haibin.tang
 * @date: 2020/8/6
 */
public class DefaultOrderBuilder implements OrderBuilder {
    private CreateOrderRequest request;
    private Order order = new Order();

    public DefaultOrderBuilder(CreateOrderRequest request) {
        this.request = request;
    }

    @Override
    public OrderBuilder check() {
        System.out.println(String.format("创建订单参数 %s", request));
        System.out.println("参数校验...");
        if (request.getProducts() == null || request.getProducts().size() < 1) {
            throw new BizException("参数错误");
        }
        return this;
    }

    @Override
    public OrderBuilder stock() {
        System.out.println("锁定库存...");
        return this;
    }

    @Override
    public OrderBuilder coupon() {
        System.out.println("优惠券抵扣计算...");
        order.setDeductionAmount(Double.valueOf(Math.random() * 3000).intValue());
        order.setCouponId(request.getCouponId());
        System.out.println("优惠券抵扣金额 " + order.getDeductionAmount());
        return this;
    }

    @Override
    public OrderBuilder countingPrice() {
        System.out.println("价格计算...");
        order.setItems(request.getProducts().stream().map(e -> {
            OrderItem item = new OrderItem();
            item.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            item.setOrderNo(order.getOrderNo());
            item.setPrice(Double.valueOf(Math.random() * 8000).intValue());
            item.setQuantity(e.getQuantity());
            item.setProductId(e.getProductId());
            return item;
        }).collect(Collectors.toList()));
        final int totalAmount = order.getItems().stream().map(OrderItem::getPrice).mapToInt(price -> price).sum();
        order.setTotalAmount(totalAmount);
        order.setFinalAmount(order.getDeductionAmount() == null ? totalAmount : totalAmount - order.getDeductionAmount());
        return this;
    }

    @Override
    public Order build() {
        System.out.println("获取建造的order对象...");
        fillOrder();
        System.out.println(order);
        return order;
    }

    private  void fillOrder() {
        order.setOrderNo("O" + System.currentTimeMillis());
        order.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
    }
}
